<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" xmlns:required="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8"/>
    <title>排班管理</title>
    <meta name="renderer" content="webkit"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <link rel="stylesheet" href="/lib/layui-v2.5.4/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all"/>
    <link rel="stylesheet" href="/css/public.css" media="all"/>
    <style>
        .layui-table-click {
            background-color: #99BBFF !important;
        }

        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
        .layui-table-cell {
            overflow: visible !important;
        }

        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select {
            margin-top: -10px;
            margin-left: -10px;
            margin-right: -0px;
        }

        td .layui-input {
            height: 34px !important;
        }

        .layui-table-grid-down {
            display: none;
        }

        .layui-layer-tips {
            display: none !important;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="layui-elem-field layuimini-search">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">排班科室</label>
                            <div class="layui-input-inline">
                                <select name="orgCode" id="orgCode">
                                    <option value="">选择科室</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">开始时间</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input dateSelect" name="startDate" id="startDate"
                                       readonly placeholder="yyyy-MM-dd"></input>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn" id="queryByn">查询</button>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-btn-group">
                                <button type="button" class="layui-btn" onclick="queryData(-1)">上一周</button>
                                <button type="button" class="layui-btn" onclick="queryData(0)">本周</button>
                                <button type="button" class="layui-btn" onclick="queryData(1)">下一周</button>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn" id="copyBtn">复制上周</button>
                            <button type="button" class="layui-btn" id="saveBtn">保存</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <table class="layui-hide" id="shiftTable"></table>

    </div>
</div>
<script type="text/html">

</script>
<script src="/lib/moment-2.24.0/moment-with-locales.min.js" charset="utf-8"></script>
<script src="/lib/layui-v2.5.4/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'layer', 'laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer,
            laydate = layui.laydate;

        var m = new Map();

        let startDate = moment().startOf('week');

        $('#startDate').val(startDate.format("YYYY-MM-DD"));
        // laydate.render({
        //     elem: '#startDate'
        //     , theme: 'molv',
        //     calendar: true,
        //     value: startDate.format("YYYY-MM-DD")
        // });


        $(function () {
            getBdsOrganizationSelectData();
            initJtcy();
        });

        function getBdsOrganizationSelectData() {
            $.ajax({
                url: "/bds/getBdsOrganizationInUum",
                method: "get",
                success: function (data) {
                    if (data.code == '0') {
                        var str = '<option value="">选择科室</option>';
                        $.each(data.data, function (key, val) {
                            str += '<option value="' + val.code + '">' + val.name + '</option>'
                        });
                        $("#orgCode").html(str);
                        form.render('select');
                    } else {
                        console.info(data.msg);
                        layer.alert(data.msg);
                    }
                }
            });
        }

        function getSelectData(orgCode) {
            if (!m.has(orgCode)) {
                m.set(orgCode, selectMaintenanceItem(orgCode));
            }
            return m.get(orgCode);
        }

        function selectMaintenanceItem(orgCode) {
            let str = '<select><option value="">请选择班次</option>';
            $.ajax({
                url: '/pts/getShiftTimeByOrgCode',
                type: 'get',
                async: false,
                data: {
                    orgCode: orgCode
                },
                success: function (data) {
                    if (data.code == '0') {
                        $.each(data.data, function (key, val) {
                            str += '<option value="' + val.timeCode + '">' + val.timeCodeName + '</option>';
                        });
                    } else {
                        console.info(data.msg);
                        layer.alert(data.msg);
                    }
                }
            });
            str += '</select>';
            return str;
        }


        $('#saveBtn').on('click', function () {
            updateCacheOrForm("shiftTable", "listTableId", "cache");
            let list = table.cache['listTableId'];
            if (table.cache['listTableId']) {
                let result = list.map(item => {
                    return {
                        id: item.id,
                        startDate: startDate.format('YYYY-MM-DD'),
                        empCode: item.empCode,
                        monday: item.monday,
                        tuesday: item.tuesday,
                        wednesday: item.wednesday,
                        thursday: item.thursday,
                        friday: item.friday,
                        saturday: item.saturday,
                        sunday: item.sunday,
                        note: item.note,
                        type: item.type
                    }
                })
                if (result.length) {
                    addRequest(result);
                } else {
                    layer.alert('没有需要保存的数据', {
                        icon: 2
                    })
                }
            }
        })

        function addRequest(obj) {
            var index = layer.msg('服务器处理中...', {
                icon: 16
                , shade: 0.08,
                time: 0
            });
            // console.info(JSON.stringify(obj));
            $.ajax({
                url: "/pts/saveShift",
                type: "POST",
                data: {
                    shiftArray: JSON.stringify(obj)
                },
                timeout: 10000,
                success: function (obj) {
                    layer.close(index);
                    table.reload('listTableId', {});
                }
            });
        }

        /***
         * 根据日期设置表头,显示一周数据
         *
         */
        function getCols(day) {
            if (day !== 0) {
                startDate.add(day, 'w');
            } else {
                startDate = moment().startOf('week');
            }

            $('#startDate').val(startDate.format("YYYY-MM-DD"));

            let new_cols = [{type: 'numbers', title: '序号', fixed: "left"}, {
                type: 'text',
                title: '姓名',
                field: 'empCodeName',
                align: 'center'
            }, {
                type: 'text',
                title: 'id',
                hide: true,
                field: 'id'
            }];
            for (let i = 0; i < 7; i++) {
                let startDate1 = startDate.clone();
                startDate1.weekday(i);
                new_cols.push({
                    field: startDate1.locale('en').format('dddd').toLowerCase(),
                    title: startDate1.format('YYYY-MM-DD') + '|' + startDate1.locale('zh-cn').format('ddd'),
                    templet: function (d) {
                        // console.info("d:" + d);
                        if (d.orgCode) {
                            return getSelectData(d.orgCode);
                        } else {
                            return '';
                        }
                    },
                    // width:'160',
                    sort: false
                });
            }
            new_cols.push({field: 'note', type: 'text', title: '备注', edit: 'text', align: 'center'});
            return [new_cols];
        }


        /***
         * op="cache",则更新表格数据，将表格编辑控件数据更新到缓存table.cache[tableCacheId];
         * op="form"，则从缓存table.cache[tableCacheId]获取数据更新表格对应的下拉框，日期等控件。
         * op: 取值cache或者form。默认form
         */
        function updateCacheOrForm(tableId, tableCacheId, op) {
            op = op || "form";
            var divForm = $("#" + tableId).next();
            var tableCache = table.cache[tableCacheId];
            var trJqs = divForm.find(".layui-table-body tr");
            trJqs.each(function () {
                var trJq = $(this);
                var dataIndex = trJq.attr("data-index");
                trJq.find("td").each(function () {
                    var tdJq = $(this);
                    var fieldName = tdJq.attr("data-field");
                    //var fieldName = selectJq.eq(0).attr("name");
                    //更新select数据
                    var selectJq = tdJq.find("select");
                    if (selectJq.length == 1) {
                        if (op == "cache") {
                            tableCache[dataIndex][fieldName] = selectJq.eq(0).val();
                        } else if (op == "form") {
                            selectJq.eq(0).val(tableCache[dataIndex][fieldName])
                        }
                    }
                });
            });
            return tableCache;
        }

        function initJtcy(tableData) {
            tableData = tableData || [];
            table.render({
                elem: '#shiftTable',
                id: 'listTableId',
                url: '/pts/getNurseShiftData',
                method: 'post',
                cols: getCols(0),
                size: 'sm',
                skin: 'line',
                height: 'full-120',
                even: true,
                where: {
                    startDate: startDate.format('YYYY-MM-DD'),
                    orgCode: $('#orgCode').val()
                },
                done: function (data, curr, count) {
                    table.cache['listTableId'] = data.data;
                    updateCacheOrForm("shiftTable", "listTableId", "form");
                    form.render();
                }
            });

        }

        window.queryData = function (day) {
            let orgCode = $('#orgCode').val();
            if (orgCode) {
                let new_cols = getCols(day);

                //执行搜索重载
                table.reload('listTableId', {
                    where: {
                        startDate: startDate.format('YYYY-MM-DD'),
                        orgCode: $('#orgCode').val()
                    },
                    cols: new_cols
                }, 'data');
            } else {
                layer.alert('请先选择科室', {
                    icon: 2
                })
            }

        }

        $('#queryByn').on('click', function () {
            let orgCode = $('#orgCode').val();
            if (orgCode) {
                table.reload('listTableId', {
                    where: {
                        startDate: startDate.format('YYYY-MM-DD'),
                        orgCode: orgCode
                    }
                }, 'data');
            } else {
                layer.alert('请先选择科室', {
                    icon: 2
                })
            }
        })

        $('#copyBtn').on('click', function () {
            let orgCode = $('#orgCode').val();
            if (orgCode) {
                table.reload('listTableId', {
                    where: {
                        startDate: startDate.clone().add(-1, 'w').format('YYYY-MM-DD'),
                        orgCode: orgCode,
                        isCopy: '1'
                    }
                }, 'data');
            } else {
                layer.alert('请先选择科室', {
                    icon: 2
                })
            }
        })
    });
</script>

</body>
</html>
